package com.zzh.h265toupin.sockets

import android.media.projection.MediaProjection
import android.util.Log
import com.zzh.h265toupin.H265Encode
import org.java_websocket.WebSocket
import org.java_websocket.WebSocketImpl
import org.java_websocket.handshake.ClientHandshake
import org.java_websocket.server.WebSocketServer
import java.lang.Exception
import java.net.InetSocketAddress

//推流端作为服务器
class SocketPushServer(port: Int) {
    private var socketServer: WebSocket? = null

    private var h265Encode: H265Encode? = null

    fun start(mediaProjection: MediaProjection) {
        webSocketServer.start()
        h265Encode = H265Encode(this, mediaProjection)
        try {
            h265Encode!!.startPush()
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    fun close() {
        try {
            socketServer?.close()
            webSocketServer.stop()
            h265Encode?.stop()
            h265Encode = null
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    fun sendData(bytes: ByteArray) {
        if (socketServer?.isOpen == true) {
            socketServer!!.send(bytes)
        }
    }

    private val webSocketServer = object : WebSocketServer(InetSocketAddress(port)) {
        override fun onOpen(conn: WebSocket?, handshake: ClientHandshake?) {
            socketServer = conn
            h265Encode?.curIFrame?.let { sendData(it) }
            Log.d("TAG_SocketServer", "SocketServer onOpen.....${conn?.remoteSocketAddress}}")

        }

        override fun onClose(conn: WebSocket?, code: Int, reason: String?, remote: Boolean) {
            Log.d("TAG_SocketServer", "SocketServer close.....")
        }

        override fun onMessage(conn: WebSocket?, message: String?) {

        }

        override fun onError(conn: WebSocket?, ex: Exception?) {
            Log.e("TAG_SocketServer", "SocketServer onError.....${ex?.localizedMessage}")
        }

        override fun onStart() {

        }

    }


}